<template>
  <!-- display内务情况-->
  <div class="dormitory-status">
    <div class="module-title">
      内务情况
      <button
        class="info-btn"
        @mouseenter="showTooltip"
        @mouseleave="hideTooltip">
        <i class="el-icon-reading"></i>
      </button>
      <!-- 悬停提示框 -->
      <div
        v-show="tooltipVisible"
        class="tooltip-box"
        :style="tooltipStyle">
        {{ dormitoryInfoText }}
      </div>
    </div>
    <div class="charts-container">
      <!-- 切换按钮 -->
      <div class="chart-tabs">
        <div
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: activeTabIndex === index }"
          @click="activeTabIndex = index"
        >
          {{ tab.name }}
        </div>
      </div>

      <!-- 总体内务情况 -->
      <div v-show="activeTabIndex === 0" class="chart-wrapper">
        <div class="chart-title">总体内务情况</div>
        <div class="inspection-date" v-if="latestInspectionDate">检查时间: {{ latestInspectionDate }}</div>
        <div ref="totalChart" class="chart"></div>
      </div>

      <!-- 1组情况 -->
      <div v-show="activeTabIndex === 1" class="chart-wrapper">
        <div class="chart-title">1组情况</div>
        <div class="inspection-date" v-if="latestInspectionDate">检查时间: {{ latestInspectionDate }}</div>
        <div ref="grade1Chart" class="chart"></div>
      </div>

      <!-- 2组情况 -->
      <div v-show="activeTabIndex === 2" class="chart-wrapper">
        <div class="chart-title">2组情况</div>
        <div class="inspection-date" v-if="latestInspectionDate">检查时间: {{ latestInspectionDate }}</div>
        <div ref="grade2Chart" class="chart"></div>
      </div>

      <!-- 3组情况 -->
      <div v-show="activeTabIndex === 3" class="chart-wrapper">
        <div class="chart-title">3组情况</div>
        <div class="inspection-date" v-if="latestInspectionDate">检查时间: {{ latestInspectionDate }}</div>
        <div ref="grade3Chart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DormitoryStatus',
  data() {
    return {
      activeTabIndex: 0,
      autoRotateTimer: null,
      isAutoRotating: true,
      rotationInterval: 5000, // 5秒轮换一次
      tabs: [
        { name: '总体情况' },
        { name: '1组情况' },
        { name: '2组情况' },
        { name: '3组情况' }
      ],
      dormitoryData: [],
      latestInspectionDate: '',
      charts: {
        totalChart: null,
        grade1Chart: null,
        grade2Chart: null,
        grade3Chart: null
      },
      // 提示框相关
      tooltipVisible: false,
      dormitoryInfoText: '',
      tooltipStyle: {
        position: 'absolute',
        top: '35px',
        left: '120px',
        zIndex: 1000
      }
    };
  },
  mounted() {
    this.loadDormitoryData();
    this.loadDormitoryInfoText();

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', this.resizeCharts);

    // 启动自动轮换
    this.startAutoRotate();
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.resizeCharts);

    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });

    // 清除定时器
    this.stopAutoRotate();
  },
  watch: {
    activeTabIndex() {
      // 当切换标签时，确保图表正确渲染
      this.$nextTick(() => {
        this.initCharts();
      });

      // 手动切换时暂停自动轮换
      this.stopAutoRotate();
      // 10秒后恢复自动轮换
      setTimeout(() => {
        this.startAutoRotate();
      }, 10000);
    }
  },
  methods: {
    async loadDormitoryData() {
      try {
        const response = await this.$displayapi.getHouseKeeping();
        if (response && response.code === '200' && Array.isArray(response.data)) {
          this.dormitoryData = response.data;
        this.latestInspectionDate = response.data[0]?.检查时间 || '5月24日';  // 设置检查时间

        // 初始化图表
        this.$nextTick(() => {
          this.initCharts();
        });
        } else {
          throw new Error('内务数据格式错误');
        }
      } catch (error) {
        console.error('获取内务信息出错:', error);
        this.$message.error('加载内务数据失败');
      }
    },

    initCharts() {
      // 初始化总体内务情况图表
      if (this.activeTabIndex === 0) {
        this.initTotalChart();
      }
      // 初始化各组内务情况图表
      else {
        const groupIndex = this.activeTabIndex - 1;
        const groupData = this.dormitoryData[groupIndex];
        if (groupData) {
          this.initGroupChart(`grade${this.activeTabIndex}Chart`, groupData);
        }
      }
    },

    initTotalChart() {
      if (!this.$refs.totalChart) return;

      // 初始化图表
      if (this.charts.totalChart) {
        this.charts.totalChart.dispose();
      }

      this.charts.totalChart = echarts.init(this.$refs.totalChart);

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          data: this.dormitoryData.map(item => item.groupName || `${item.groupName}组`),
          textStyle: { color: '#d3d6dd', fontSize: 16 },
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['内务质量', '物品摆放', '卫生清洁'],
          axisLine: { lineStyle: { color: '#d3d6dd' } },
          axisLabel: { color: '#d3d6dd', fontSize: 16 }
        },
        yAxis: {
          type: 'value',
          name: '问题人数',
          nameTextStyle: { color: '#d3d6dd', fontSize: 16 },
          axisLine: { lineStyle: { color: '#d3d6dd' } },
          axisLabel: { color: '#d3d6dd', fontSize: 16 },
          splitLine: { lineStyle: { color: 'rgba(211, 214, 221, 0.1)' } }
        },
        series: this.dormitoryData.map(group => ({
          name: group.groupName || `${group.groupName}组`,
            type: 'bar',
          data: [
            Number(group.qualityCount) || 0,
            Number(group.placementCount) || 0,
            Number(group.cleanCount) || 0
          ],
            itemStyle: {
            color:
              group.groupName === '1组' || group.groupName === '1' || group.groupName === 1 ? '#4992ff' :
              group.groupName === '2组' || group.groupName === '2' || group.groupName === 2 ? '#7cffb2' :
              '#ff6e76'
              }
        }))
      };

      this.charts.totalChart.setOption(option);
    },

    initGroupChart(chartRef, groupData) {
      if (!this.$refs[chartRef]) return;

      if (this.charts[chartRef]) {
        this.charts[chartRef].dispose();
      }

      this.charts[chartRef] = echarts.init(this.$refs[chartRef]);

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['内务质量', '物品摆放', '卫生清洁'],
          axisLine: { lineStyle: { color: '#d3d6dd' } },
          axisLabel: { color: '#d3d6dd', fontSize: 16 }
        },
        yAxis: {
          type: 'value',
          name: '问题人数',
          nameTextStyle: { color: '#d3d6dd', fontSize: 16 },
          axisLine: { lineStyle: { color: '#d3d6dd' } },
          axisLabel: { color: '#d3d6dd', fontSize: 16 },
          splitLine: { lineStyle: { color: 'rgba(211, 214, 221, 0.1)' } }
        },
        series: [{
            name: '问题人数',
            type: 'bar',
          data: [
            Number(groupData.qualityCount) || 0,
            Number(groupData.placementCount) || 0,
            Number(groupData.cleanCount) || 0
          ],
            itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.getGroupColor(groupData.groupName, true) },
              { offset: 1, color: this.getGroupColor(groupData.groupName, false) }
                      ])
              }
        }]
      };

      this.charts[chartRef].setOption(option);
    },

    getGroupColor(groupName, isStart) {
      switch(groupName) {
        case '1组':
          return isStart ? '#f6c3a5' : '#e86110';
        case '2组':
          return isStart ? '#a8e6cf' : '#41b883';
        case '3组':
          return isStart ? '#c4b5fd' : '#8b5cf6';
        default:
          return isStart ? '#83bff6' : '#188df0';
      }
    },

    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    },

    // 开始自动轮换
    startAutoRotate() {
      if (this.autoRotateTimer) {
        clearInterval(this.autoRotateTimer);
      }

      this.isAutoRotating = true;
      this.autoRotateTimer = setInterval(() => {
        // 计算下一个要显示的图表索引
        const nextIndex = (this.activeTabIndex + 1) % this.tabs.length;
        this.activeTabIndex = nextIndex;
        this.$nextTick(() => {
          this.initCharts();
        });
      }, this.rotationInterval);
    },

    // 停止自动轮换
    stopAutoRotate() {
      if (this.autoRotateTimer) {
        clearInterval(this.autoRotateTimer);
        this.autoRotateTimer = null;
      }
      this.isAutoRotating = false;
    },

    // 加载内务情况说明文本
    async loadDormitoryInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"3、"后面的文本，直到下一个序号或文件结束
          const regex = /3、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.dormitoryInfoText = match[1].trim();
            console.log('内务情况说明文本:', this.dormitoryInfoText);
          } else {
            console.error('未找到内务情况说明文本');
            this.dormitoryInfoText = '第一百四十二条  内务设置应当利于战备，方便工作、学习、生活，因地制宜，整齐划一，符合卫生和安全要求，杜绝形式主义。';
          }
        } else {
          console.error('加载内务情况说明文本失败');
          this.dormitoryInfoText = '第一百四十二条  内务设置应当利于战备，方便工作、学习、生活，因地制宜，整齐划一，符合卫生和安全要求，杜绝形式主义。';
        }
      } catch (error) {
        console.error('加载内务情况说明文本出错:', error);
        this.dormitoryInfoText = '第一百四十二条  内务设置应当利于战备，方便工作、学习、生活，因地制宜，整齐划一，符合卫生和安全要求，杜绝形式主义。';
      }
    },

    // 显示提示框
    showTooltip() {
      this.tooltipVisible = true;
    },

    // 隐藏提示框
    hideTooltip() {
      this.tooltipVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.dormitory-status {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .module-title {
    font-size: 22px;
    color: #68d8fe;
    margin-bottom: 15px;
    margin-left: 20px;
    margin-top: 10px;
    padding-left: 5px;
    font-weight: bold;
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    gap: 10px;

    .info-btn {
      background: rgba(104, 216, 254, 0.2);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 4px;
      color: #68d8fe;
      cursor: pointer;
      padding: 4px 8px;
      font-size: 16px;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(104, 216, 254, 0.3);
        border-color: rgba(104, 216, 254, 0.8);
        color: #ffffff;
        transform: scale(1.05);
      }

      i {
        font-size: 14px;
      }
    }

    .tooltip-box {
      background: rgba(19, 25, 47, 0.95);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 6px;
      padding: 12px 16px;
      color: #d3d6dd;
      font-size: 18px;
      line-height: 1.6;
      max-width: 350px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(10px);
      word-wrap: break-word;
      white-space: normal;

      &::before {
        content: '';
        position: absolute;
        top: -6px;
        left: 20px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-bottom: 6px solid rgba(104, 216, 254, 0.5);
      }

      &::after {
        content: '';
        position: absolute;
        top: -5px;
        left: 21px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 5px solid rgba(19, 25, 47, 0.95);
      }
    }
  }

  .charts-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .chart-tabs {
      display: flex;
      margin-bottom: 15px;
      background-color: rgba(19, 25, 47, 0.5);
      border-radius: 4px;
      padding: 3px;

      .tab-item {
        flex: 1;
        text-align: center;
        padding: 8px 0;
        cursor: pointer;
        color: #d3d6dd;
        border-radius: 4px;
        transition: all 0.3s ease;
        font-size: 18px;

        &:hover {
          background-color: rgba(104, 216, 254, 0.1);
        }

        &.active {
          background-color: rgba(104, 216, 254, 0.2);
          color: #68d8fe;
        }
      }
    }

    .chart-wrapper {
      flex: 1;
      position: relative;

      .chart-title {
        font-size: 20px;
        color: #68d8fe;
        margin-bottom: 8px;
      }

      .inspection-date {
        position: absolute;
        top: 0;
        right: 20px;
        font-size: 18px;
        color: #68d8fe;
        background-color: rgba(19, 25, 47, 0.5);
        padding: 4px 8px;
        border-radius: 4px;
        border-left: 2px solid #68d8fe;
      }

      .chart {
        width: 100%;
        height: calc(100% - 30px);
      }
    }
  }
}
</style>
